<?php
/**
 * Created by PhpStorm.
 * User: 29620
 * Date: 2021/10/27
 * Time: 9:35
 */
namespace app\admin\controller;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Filesystem;
class Upload
{
    public static function upload($filed = 'img',$string = true)
    {
        //判断是否上传对应字段的图片
        try{
            $files = Request::file($filed);
        }catch (\Exception $e){
            return [false,'没上传图片1'];
        }
        //没接到上传图片字段值
        if(!$files) return [false,'没上传图片2'];
        //判断单图多图
        if(is_array($files)){
            //多图上传
            try{
                validate(['image'=>'fileSize:10240000|fileExt:jpg,png,jpeg,gif'])->check(['image'=>$files]);
            }catch (ValidateException $e){
                return "<script>alert('后缀名不符合规范或者图片超过10240000');history.back();</script>";
                //return $e->getMessage();
            }
            $path = [];
            foreach ($files as $file){
                $img = Filesystem::putFile( 'img', $file);
                $path[] = str_replace('\\','/',$img);
            }
            if($string) $path = implode(',',$path);
        }else{
            //上传验证 fileSize最大字符 fileExt后缀 fileMime类型  image尺寸
            try{
                validate(['image'=>'fileSize:10240000|fileExt:jpg,png,jpeg,gif'])->check(['image'=>$files]);
            }catch (ValidateException $e){
                return "<script>alert('后缀名不符合规范或者图片超过10240000');history.back();</script>";
                //return $e->getMessage();
            }
            //单图上传
            $path = Filesystem::putFile( 'img', $files);
            $path = str_replace('\\','/',$path);
        }
        return [true,$path];
    }


    public static function removeImg($img)
    {
        if (is_array($img)){
            foreach ($img as $v){
                static::removeTwo($v);
            }
        }else{
            self::removeTwo($img);
        }
    }

    public static function removeTwo($img)
    {
        if(!$img) return ;
        $lin = app()->getRootPath().'public/static/admin/linshi/'.$img;
        $zheng = app()->getRootPath().'public/static/admin/'.$img;
        $dir = app()->getRootPath().'public/static/admin/img/'.date('Ymd',time());
        if (!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        rename($lin,$zheng);
    }




}



























